package cn.stylefeng.guns.core.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 下载文件
 * 
 * @author FH
 * @version 1.0
 */
public class DownloadFileUtil {

	/**
	 * @param filePath 需要下载的文件路径
	 * @param fileName 下载到浏览器的文件名
	 * @param request
	 * @param response
	 */
	public static void downloadFile(String filePath,String fileName,HttpServletRequest request, HttpServletResponse response){
		try {
			fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
			// 设置响应头控制浏览器以下载的形式打开文件
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			// 文件的存放路径
			InputStream in = new FileInputStream(filePath);
			int count =0;
			byte[] by = new byte[1024];
			//通过response对象获取OutputStream流
			OutputStream out=  response.getOutputStream();
			//将缓冲区的数据输出到浏览器
			while((count=in.read(by))!=-1){
				out.write(by, 0, count);
			}
			in.close();
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void downloadFile(InputStream in,String fileName,HttpServletRequest request, HttpServletResponse response){
		try {
			fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
			// 设置响应头控制浏览器以下载的形式打开文件
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			// 文件的存放路径
			int count =0;
			byte[] by = new byte[1024];
			//通过response对象获取OutputStream流
			OutputStream out=  response.getOutputStream();
			//将缓冲区的数据输出到浏览器
			while((count=in.read(by))!=-1){
				out.write(by, 0, count);
			}
			in.close();
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
